
<!DOCTYPE HTML>
<html lang="" >
    <head>
        <meta charset="UTF-8">
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>特殊指令ref的工作原理 · petite-vue源码剖析</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="GitBook 3.2.3">
        <meta name="author" content="^_^肥仔John">
        
        
    
    <link rel="stylesheet" href="../../gitbook/style.css">

    
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-search-pro/search.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-code/plugin.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-back-to-top-button/plugin.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-tbfed-pagefooter/footer.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-chapter-fold/chapter-fold.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-expandable-chapters/expandable-chapters.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-splitter/splitter.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-anchor-navigation-ex/style/plugin.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-donate/plugin.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-highlight/website.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-fontsettings/website.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-theme-comscore/test.css">
                
            
        

    

    
        
    
        
    
        
    
        
    
        
    
        
    

        
    
    
    <meta name="HandheldFriendly" content="true"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../../gitbook/images/apple-touch-icon-precomposed-152.png">
    <link rel="shortcut icon" href="../../gitbook/images/favicon.ico" type="image/x-icon">

    
    <link rel="next" href="../5_tips_for_template.html" />
    
    
    <link rel="prev" href="3_bidirectional_binding.html" />
    

    </head>
    <body>
        
<div class="book">
    <div class="book-summary">
        
            
<div id="book-search-input" role="search">
    <input type="text" placeholder="Type to search" />
</div>

            
                <nav role="navigation">
                


<ul class="summary">
    
    

    

    
        
        <li class="header">前言</li>
        
        
    
        <li class="chapter " data-level="1.1" data-path="../../">
            
                <a href="../../">
            
                    
                    《Petite-Vue源码剖析》简介
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="../../0_intro/1_reason_for_source_reading.html">
            
                <a href="../../0_intro/1_reason_for_source_reading.html">
            
                    
                    为什么要读源码
            
                </a>
            

            
        </li>
    

    
        
        <li class="header">在线渲染</li>
        
        
    
        <li class="chapter " data-level="2.1" data-path="../0_intro.html">
            
                <a href="../0_intro.html">
            
                    
                    章节介绍
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="2.2" data-path="../1_start_from_static_view.html">
            
                <a href="../1_start_from_static_view.html">
            
                    
                    从静态视图首次渲染开始
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="2.3" data-path="../2_initial_rendering_and_rerendering_for_v-if.html">
            
                <a href="../2_initial_rendering_and_rerendering_for_v-if.html">
            
                    
                    条件v-if的首次渲染和重新渲染
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="2.4" data-path="../3_initial_rendering_and_rerendering_for_v-for.html">
            
                <a href="../3_initial_rendering_and_rerendering_for_v-for.html">
            
                    
                    循环v-for的首次渲染和重新渲染
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="2.5" data-path="1_attribute_binding.html">
            
                <a href="1_attribute_binding.html">
            
                    
                    属性绑定v-bind的工作原理
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="2.6" data-path="2_event_binding.html">
            
                <a href="2_event_binding.html">
            
                    
                    事件绑定v-on的工作原理
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="2.7" data-path="3_bidirectional_binding.html">
            
                <a href="3_bidirectional_binding.html">
            
                    
                    双向绑定v-model的工作原理
            
                </a>
            

            
        </li>
    
        <li class="chapter active" data-level="2.8" data-path="4_ref.html">
            
                <a href="4_ref.html">
            
                    
                    特殊指令ref的工作原理
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="2.9" data-path="../5_tips_for_template.html">
            
                <a href="../5_tips_for_template.html">
            
                    
                    优化手段template的原理和使用技巧
            
                </a>
            

            
        </li>
    

    
        
        <li class="header">响应式系统</li>
        
        
    
        <li class="chapter " data-level="3.1" data-path="../../2_reactivity_system/0_intro.html">
            
                <a href="../../2_reactivity_system/0_intro.html">
            
                    
                    章节介绍
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="3.2" data-path="../../2_reactivity_system/1_reactive_object_array.html">
            
                <a href="../../2_reactivity_system/1_reactive_object_array.html">
            
                    
                    逐行解读reactive如何构建对象和数组的响应式对象
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="3.3" data-path="../../2_reactivity_system/2_reactive_map_set.html">
            
                <a href="../../2_reactivity_system/2_reactive_map_set.html">
            
                    
                    逐行解读reactive如何构建Map和Set的响应式对象
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="3.4" data-path="../../2_reactivity_system/3_register_side_effect.html">
            
                <a href="../../2_reactivity_system/3_register_side_effect.html">
            
                    
                    逐行解读effect如何注册副作用函数
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="3.5" data-path="../../2_reactivity_system/4_cleanup_algorithm.html">
            
                <a href="../../2_reactivity_system/4_cleanup_algorithm.html">
            
                    
                    依赖清理优化算法详解-算法思路
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="3.6" data-path="../../2_reactivity_system/5_smi.html">
            
                <a href="../../2_reactivity_system/5_smi.html">
            
                    
                    依赖清理优化算法详解-基于JavaScript引擎的SMI进一步压榨性能
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="3.7" data-path="../../2_reactivity_system/6_trigger_and_scheduler.html">
            
                <a href="../../2_reactivity_system/6_trigger_and_scheduler.html">
            
                    
                    逐行解读trigger和调度器
            
                </a>
            

            
        </li>
    

    
        
        <li class="header">沙箱模型</li>
        
        
    
        <li class="chapter " data-level="4.1" data-path="../../3_sandbox.html">
            
                <a href="../../3_sandbox.html">
            
                    
                    模板表达式的沙箱模型
            
                </a>
            

            
        </li>
    

    

    <li class="divider"></li>

    <li>
        <a href="https://www.gitbook.com" target="blank" class="gitbook-link">
            Published with GitBook
        </a>
    </li>
</ul>


                </nav>
            
        
    </div>

    <div class="book-body">
        
            <div class="body-inner">
                
                    

<div class="book-header" role="navigation">
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href="../.." >特殊指令ref的工作原理</a>
    </h1>
</div>




                    <div class="page-wrapper" tabindex="-1" role="main">
                        <div class="page-inner">
                            
<div id="book-search-results">
    <div class="search-noresults">
    
                                <section class="normal markdown-section">
                                
                                <div id="anchor-navigation-ex-navbar"><i class="fa fa-navicon"></i><ul><li><span class="title-icon "></span><a href="#&#x7279;&#x6B8A;&#x6307;&#x4EE4;ref&#x7684;&#x5DE5;&#x4F5C;&#x539F;&#x7406;"><b>1. </b>&#x7279;&#x6B8A;&#x6307;&#x4EE4;ref&#x7684;&#x5DE5;&#x4F5C;&#x539F;&#x7406;</a></li><ul><li><span class="title-icon "></span><a href="#&#x6DF1;&#x5165;ref&#x5DE5;&#x4F5C;&#x539F;&#x7406;"><b>1.1. </b>&#x6DF1;&#x5165;ref&#x5DE5;&#x4F5C;&#x539F;&#x7406;</a></li></ul></ul></div><h1 id="&#x7279;&#x6B8A;&#x6307;&#x4EE4;ref&#x7684;&#x5DE5;&#x4F5C;&#x539F;&#x7406;"><a name="&#x7279;&#x6B8A;&#x6307;&#x4EE4;ref&#x7684;&#x5DE5;&#x4F5C;&#x539F;&#x7406;" class="anchor-navigation-ex-anchor" href="#&#x7279;&#x6B8A;&#x6307;&#x4EE4;ref&#x7684;&#x5DE5;&#x4F5C;&#x539F;&#x7406;"><i class="fa fa-link" aria-hidden="true"></i></a>1. &#x7279;&#x6B8A;&#x6307;&#x4EE4;ref&#x7684;&#x5DE5;&#x4F5C;&#x539F;&#x7406;</h1>
<p><code>ref</code>&#x5185;&#x90E8;&#x7684;&#x5DE5;&#x4F5C;&#x539F;&#x7406;&#x5341;&#x5206;&#x7B80;&#x5355;&#xFF0C;&#x5176;&#x5B9E;&#x5C31;&#x662F;&#x5C06;&#x6307;&#x4EE4;<code>ref</code>&#x3001;<code>:ref</code>&#x6216;<code>v-bind:ref</code>&#x6807;&#x8BC6;&#x7684;&#x5143;&#x7D20;&#x5B9E;&#x4F8B;&#x5B58;&#x50A8;&#x5230;&#x5F53;&#x524D;&#x4F5C;&#x7528;&#x57DF;&#x7684;<code>$refs</code>&#x5BF9;&#x8C61;&#x4E2D;&#xFF0C;&#x90A3;&#x4E48;&#x6211;&#x4EEC;&#x5C31;&#x53EF;&#x4EE5;&#x901A;&#x8FC7;<code>this.$refs</code>&#x83B7;&#x53D6;&#x5BF9;&#x5E94;&#x7684;&#x5143;&#x7D20;&#x5B9E;&#x4F8B;&#x3002;&#x4F46;&#x7531;&#x4E8E;&#x4F5C;&#x7528;&#x57DF;&#x7EE7;&#x627F;&#x4E0A;&#x6709;&#x70B9;&#x5C0F;&#x7A8D;&#x95E8;&#xFF0C;&#x6240;&#x4EE5;&#x6211;&#x4EEC;&#x80FD;&#x4ECE;<code>this.$refs</code>&#x83B7;&#x53D6;&#x7684;&#x5143;&#x7D20;&#x5B9E;&#x4F8B;&#x8FD8;&#x662F;&#x9700;&#x8981;&#x6CE8;&#x610F;&#x4E00;&#x4E0B;&#x3002;&#x4E0B;&#x9762;&#x8BA9;&#x6211;&#x4E3A;&#x4F60;&#x4E00;&#x4E00;&#x9053;&#x6765;&#x5427;&#xFF01;</p>
<h2 id="&#x6DF1;&#x5165;ref&#x5DE5;&#x4F5C;&#x539F;&#x7406;"><a name="&#x6DF1;&#x5165;ref&#x5DE5;&#x4F5C;&#x539F;&#x7406;" class="anchor-navigation-ex-anchor" href="#&#x6DF1;&#x5165;ref&#x5DE5;&#x4F5C;&#x539F;&#x7406;"><i class="fa fa-link" aria-hidden="true"></i></a>1.1. &#x6DF1;&#x5165;ref&#x5DE5;&#x4F5C;&#x539F;&#x7406;</h2>
<pre><code class="lang-ts"><span class="hljs-comment">//&#x6587;&#x4EF6; ./src/directives/ref.ts</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> ref: Directive = ({
  el,
  ctx: {
    scope: { $refs }
  },
  <span class="hljs-keyword">get</span>,
  effect
}) =&gt; {
  <span class="hljs-keyword">let</span> prevRef: <span class="hljs-built_in">any</span>
  effect(() =&gt; {
    <span class="hljs-comment">// &#x83B7;&#x53D6;&#x6307;&#x5411;&#x5143;&#x7D20;&#x7684;&#x5C5E;&#x6027;&#x540D;&#x79F0;</span>
    <span class="hljs-keyword">const</span> ref = <span class="hljs-keyword">get</span>()
    $refs[ref] = el
    <span class="hljs-comment">// &#x7531;&#x4E8E;&#x5C5E;&#x6027;&#x540D;&#x79F0;&#x662F;&#x53EF;&#x4EE5;&#x52A8;&#x6001;&#x751F;&#x6210;&#x7684;(:ref=&quot;name&quot;)&#xFF0C;&#x82E5;&#x65B0;&#x65E7;&#x5BF9;&#x5E94;&#x7684;&#x5C5E;&#x6027;&#x540D;&#x79F0;&#x4E0D;&#x540C;&#xFF0C;&#x5219;&#x6E05;&#x7406;&#x65E7;&#x5C5E;&#x6027;</span>
    <span class="hljs-keyword">if</span> (prevRef &amp;&amp; ref != prevRef) {
      <span class="hljs-keyword">delete</span> $refs[prevRef]
    }
    prevRef = ref
  })

  <span class="hljs-keyword">return</span> () =&gt; {
    prevRef &amp;&amp; <span class="hljs-keyword">delete</span> $refs[prevRef]
  }
}
</code></pre>
<p>&#x8FD9;&#x6BB5;&#x5B9E;&#x73B0;&#x662F;&#x4E0D;&#x662F;&#x8A00;&#x7B80;&#x610F;&#x8D45;&#x5462;&#xFF1F;&#x73B0;&#x5728;&#x8BA9;&#x6211;&#x4EEC;&#x628A;&#x76EE;&#x5149;&#x8F6C;&#x5411;&#x4E0A;&#x4E0B;&#x6587;&#x5BF9;&#x8C61;(Context)&#x7684;&#x6784;&#x5EFA;&#x5427;</p>
<pre><code class="lang-ts"><span class="hljs-comment">//&#x6587;&#x4EF6; ./src/context.ts</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> createScopedContext = (ctx: Context, data = {}) =&gt; {
  <span class="hljs-keyword">const</span> parentScope = ctx.scope
  <span class="hljs-keyword">const</span> mergedScope = <span class="hljs-built_in">Object</span>.create(parentScope)
  <span class="hljs-built_in">Object</span>.defineProperties(mergedScope, <span class="hljs-built_in">Object</span>.getOwnPropertyDescriptors(data))
  <span class="hljs-comment">// $refs&#x6784;&#x6210;$refs&#x5BF9;&#x8C61;&#x7684;&#x539F;&#x578B;&#x94FE;</span>
  mergedScope.$refs = <span class="hljs-built_in">Object</span>.create(parentScope.$refs)
  <span class="hljs-comment">// ......</span>
}
</code></pre>
<p>$refs&#x6784;&#x6210;$refs&#x5BF9;&#x8C61;&#x7684;&#x539F;&#x578B;&#x94FE;&#xFF0C;&#x90A3;&#x4E48;&#x6211;&#x4EEC;&#x5C31;&#x53EF;&#x4EE5;&#x8FD9;&#x6837;&#x5F15;&#x7528;&#x5143;&#x7D20;&#x5B9E;&#x4F8B;</p>
<pre><code class="lang-js">createApp({
  App: {
    $template: <span class="hljs-string">`
    &lt;div ref=&quot;container&quot;&gt;
      &lt;div v-scope=&quot;Modal&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;
    `</span>,
    Modal: {
      $template: <span class="hljs-string">`
      &lt;button @click=&quot;handleHide&quot;&gt;Hide&lt;/button&gt;
      `</span>,
      handleHide() {
        <span class="hljs-keyword">this</span>.$refs.container.style.display = <span class="hljs-string">&apos;none&apos;</span>
      }
    }
  }
}).mount(<span class="hljs-string">&apos;[v-scope]&apos;</span>)
</code></pre>
<script type="text/javascript">
  /**
   * Donation
   */
  function showQR(){
    var rewardButton = document.getElementById('rewardButton')
    var qr = document.getElementById('QR')
    if (rewardButton) {
      rewardButton.style.display = 'none'
    }
    if (qr) {
      qr.style.display = 'block'
    }
  }
  setInterval(showQR, 1000)

  /**
   * Baidu analysis
   */
  var _hmt = _hmt || [];
  (function() {
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?8bca1e3aa362a7f85dbe8304cff65225";
    var s = document.getElementsByTagName("script")[0]; 
    s.parentNode.insertBefore(hm, s);
  })();
</script>


<footer class="page-footer"><span class="copyright">Copyright &#xA9; fsjohnhuang 2022 all right reserved&#xFF0C;powered by Gitbook</span><span class="footer-modification">File Modify: 
2022-04-26 09:47:01
</span></footer>
                                
                                </section>
                            
    </div>
    <div class="search-results">
        <div class="has-results">
            
            <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
            <ul class="search-results-list"></ul>
            
        </div>
        <div class="no-results">
            
            <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
            
        </div>
    </div>
</div>

                        </div>
                    </div>
                
            </div>

            
                
                <a href="3_bidirectional_binding.html" class="navigation navigation-prev " aria-label="Previous page: 双向绑定v-model的工作原理">
                    <i class="fa fa-angle-left"></i>
                </a>
                
                
                <a href="../5_tips_for_template.html" class="navigation navigation-next " aria-label="Next page: 优化手段template的原理和使用技巧">
                    <i class="fa fa-angle-right"></i>
                </a>
                
            
        
    </div>

    <script>
        var gitbook = gitbook || [];
        gitbook.push(function() {
            gitbook.page.hasChanged({"page":{"title":"特殊指令ref的工作原理","level":"2.8","depth":1,"next":{"title":"优化手段template的原理和使用技巧","level":"2.9","depth":1,"path":"1_online_rendering/5_tips_for_template.md","ref":"1_online_rendering/5_tips_for_template.md","articles":[]},"previous":{"title":"双向绑定v-model的工作原理","level":"2.7","depth":1,"path":"1_online_rendering/4_directives/3_bidirectional_binding.md","ref":"1_online_rendering/4_directives/3_bidirectional_binding.md","articles":[]},"dir":"ltr"},"config":{"plugins":["-lunr","-search","-sharing","theme-comscore","search-pro","code","back-to-top-button","tbfed-pagefooter","chapter-fold","expandable-chapters","splitter","anchor-navigation-ex","donate","sharing-plus","baidu"],"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"pluginsConfig":{"tbfed-pagefooter":{"copyright":"Copyright &copy fsjohnhuang 2022"},"chapter-fold":{},"splitter":{},"search-pro":{},"sharing-plus":{"qq":false,"all":["facebook","google","twitter","instapaper","linkedin","pocket","stumbleupon"],"douban":false,"facebook":true,"weibo":false,"instapaper":false,"whatsapp":false,"hatenaBookmark":false,"twitter":true,"messenger":false,"line":false,"vk":false,"pocket":true,"google":false,"viber":false,"stumbleupon":false,"qzone":false,"linkedin":false},"code":{"copyButtons":true},"donate":{"alipay":"","alipayText":"支付宝打赏","button":"赞赏","title":"","wechat":"/petite-vue-source-reading/images/wechat.jpg","wechatText":"微信打赏"},"fontsettings":{"theme":"white","family":"sans","size":2},"highlight":{},"anchor-navigation-ex":{"associatedWithSummary":true,"float":{"floatIcon":"fa fa-navicon","level1Icon":"","level2Icon":"","level3Icon":"","showLevelIcon":false},"mode":"float","multipleH1":true,"pageTop":{"level1Icon":"","level2Icon":"","level3Icon":"","showLevelIcon":false},"printLog":false,"showGoTop":false,"showLevel":true},"theme-comscore":{},"back-to-top-button":{},"baidu":{"token":"8bca1e3aa362a7f85dbe8304cff65225"},"sharing":{"qq":false,"all":["qq","qzone","weibo","whatsapp","twitter","facebook","line"],"douban":false,"facebook":false,"weibo":false,"instapaper":false,"whatsapp":false,"hatenaBookmark":false,"twitter":false,"messenger":false,"line":false,"vk":false,"pocket":false,"google":false,"viber":false,"stumbleupon":false,"qzone":false,"linkedin":false},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false},"expandable-chapters":{}},"theme":"default","author":"^_^肥仔John","lang":"zh-cn","pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"isbn":"","variables":{},"title":"petite-vue源码剖析","gitbook":"*","description":""},"file":{"path":"1_online_rendering/4_directives/4_ref.md","mtime":"2022-04-26T01:47:01.528Z","type":"markdown"},"gitbook":{"version":"3.2.3","time":"2022-05-05T01:20:11.998Z"},"basePath":"../..","book":{"language":""}});
        });
    </script>
</div>

        
    <script src="../../gitbook/gitbook.js"></script>
    <script src="../../gitbook/theme.js"></script>
    
        
        <script src="../../gitbook/gitbook-plugin-search-pro/jquery.mark.min.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-search-pro/search.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-code/plugin.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-back-to-top-button/plugin.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-chapter-fold/chapter-fold.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-expandable-chapters/expandable-chapters.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-splitter/splitter.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-donate/plugin.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-sharing-plus/buttons.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-baidu/plugin.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-theme-comscore/test.js"></script>
        
    

    </body>
</html>

